﻿using Reap.AzureResource.API;

using WebActivator;

[assembly: PreApplicationStartMethod(typeof(NinjectWebCommon),"Start")]
[assembly: ApplicationShutdownMethod(typeof(NinjectWebCommon),"Stop")]

namespace Reap.AzureResource.API {
	using System;
	using System.Web;
	using System.Web.Http;

	using Microsoft.Web.Infrastructure.DynamicModuleHelper;

	using Ninject;
	using Ninject.Web.Common;

	using Reap.AzureResource.Data.Infrastructure;
	using Reap.AzureResource.Data.Repositories;
	using Reap.AzureResource.Service;

	public class NinjectWebCommon {
		#region Static Fields

		private static readonly Bootstrapper Bootstrapper = new Bootstrapper();

		#endregion

		#region Public Methods and Operators

		public static void Start() {

			DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
			DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
			Bootstrapper.Initialize(CreateKernel);
		}

		public static void Stop() {
			Bootstrapper.ShutDown();
		}

		#endregion

		#region Methods

		private static IKernel CreateKernel() {
			var kernel = new StandardKernel();
			try {
				kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
				kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

				RegisterServices(kernel);

				// Install our Ninject-based IDependencyResolver into the Web API config
				GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

				return kernel;
			} catch {
				kernel.Dispose();
				throw;
			}
		}

		private static void RegisterServices(IKernel kernel) {
			kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>().InRequestScope();
			kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
			kernel.Bind<ILocationRepository>().To<LocationRepository>().InRequestScope();
			kernel.Bind<IResourceRepository>().To<ResourceRepository>().InRequestScope();
			kernel.Bind<IResourceActivityRepository>().To<ResourceActivityRepository>().InRequestScope();
			kernel.Bind<ILocationService>().To<LocationService>().InRequestScope();
			kernel.Bind<IResourceService>().To<ResourceService>().InRequestScope();
			kernel.Bind<IResourceActivityService>().To<ResourceActivityService>().InRequestScope();
		}

		#endregion
	}
}